package com.lzp.java.concurrent.threadcore.threadandobject.object;

/**
 * 交替打印0-100奇偶数--使用wait和notify实现
 * 1. 解决只用synchronized的弊端
 * 2. while循环放入到synchronized代码块中，不停测试线程唤醒条件是否满足
 * 同时用于避免虚假唤醒
 *
 * @author lzp
 * @date 2020/02/08
 */
public class PrintNumberByWaitAndNotify {
    private static int count = 0;
    /**
     * 定义锁
     */
    private static final Object lock = new Object();

    public static void main(String[] args) throws InterruptedException {
        new Thread(new PrintTask(), "偶数线程").start();
        Thread.sleep(100);
        new Thread(new PrintTask(), "奇数线程").start();
    }

    static class PrintTask implements Runnable {
        @Override
        public void run() {
            synchronized (lock) {
                while (count <= 100) {
                    System.out.println(Thread.currentThread().getName() + "打印" + count++);
                    lock.notify();
                    if (count <= 100) {
                        try {
                            // 如果任务没有结束，释放锁
                            lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    }
}
